package com.atguigu.tingshu.album.mq;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TrackReceiver {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    TrackInfoService trackInfoService;

    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void updateTrackStatReceiver(ConsumerRecord<String,String> record){
        String json = record.value();
        if (!StringUtils.isEmpty(json)) {
            TrackStatMqVo trackStatMqVo = JSON.parseObject(json, TrackStatMqVo.class);
            String redisKey = "track:stat:idempotent" + trackStatMqVo.getBusinessNo();
            Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, JSON.toJSONString(trackStatMqVo), 1, TimeUnit.HOURS);
            if (Boolean.TRUE.equals(aBoolean)){
                trackInfoService.updateTrackStat(trackStatMqVo);
                log.info("更新声音播放量成功了");
            }

        }
    }

}
